﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ncp.Business;
using ncp.Business.Common;

namespace ncp.Web.page
{
    public partial class Product : System.Web.UI.Page
    {
        int id;
        protected void Page_Load(object sender, EventArgs e)
        {
            AjaxPro.Utility.RegisterTypeForAjax(typeof(Product));
            if (!IsPostBack)
            {
                var requestid = Request.QueryString["id"];
                if (requestid==null||!int.TryParse(EncryptHelper.DecryptString(requestid),out id))
                {
                    Response.Redirect("/error.html");
                }
                GetProductInfo();
            }
        }

        //获取产品和用户信息
        private void GetProductInfo()
        {
            //产品信息
            string where = "Product_Id=" + id;
            if (Request.QueryString["preview"]==null)
            {
                where += " and Product_Status=1";
            }
            var dt = ProductInfoBll.GetProductInfoTable(where, "", CommonConst.DB_Name);
            if (dt.Rows.Count > 0)
            {
                lbName.Text = dt.Rows[0]["Product_Title"].ToString();
                lbNum.Text = dt.Rows[0]["Product_Amount"].ToString()+" "+ dt.Rows[0]["Product_Unit"].ToString();
                lbStart.Text = Convert.ToDateTime(dt.Rows[0]["Product_StartTime"].ToString()).ToString("yyyy-MM-dd");
                lbEnd.Text = Convert.ToDateTime(dt.Rows[0]["Product_EndTime"].ToString()).ToString("yyyy-MM-dd");
                ltIntro.Text = dt.Rows[0]["Product_Remark"].ToString();
                lbType.Text = dt.Rows[0]["GC_Name"].ToString();
                lbUserName.Text = dt.Rows[0]["Client_Name"].ToString();
                lbContact.Text = dt.Rows[0]["User_Contact"].ToString();
                lbCellPhone.Text = dt.Rows[0]["User_CellPhone"].ToString();
                lbTelPhone.Text = dt.Rows[0]["User_TelPhone"].ToString();
                lbEmail.Text = dt.Rows[0]["User_Email"].ToString();
                lbAddr.Text = dt.Rows[0]["User_Address"].ToString();

                //获取推荐同类产品
                var dtInfos = ProductInfoBll.GetGoodsinfobyPId(dt.Rows[0]["GC_Id"].ToString(),  CommonConst.DB_Name);
                string G_Id = "";
                foreach (DataRow row in dtInfos.Rows)
                {
                    G_Id += "," + row["G_Id"];
                }
                if (G_Id != "")
                {
                    G_Id = G_Id.Substring(1);
                }
                string field = " top 7 a.*";
                string orderBy = "order by a.Product_StartTime,b.User_Points desc";

                //获取VIP同类产品
                string whereVip = "where a.G_Id in(" + G_Id + ") and getdate()<Vip_EndDate ";
                var dtVip = ProductInfoBll.GetProductInfoJoinTable(field, orderBy, whereVip, null, CommonConst.DB_Name);
                repSame.DataSource = dtVip;
                repSame.DataBind();
            }
        }
        //获取用户店铺
        public string GetShopId()
        {
            var userId = 0;
            string where = "Product_Id=" + id;
            if (Request.QueryString["preview"]==null)
            {
                where += " and Product_Status=1";
            }
            var dt = ProductInfoBll.GetProductInfoTable(where, "", CommonConst.DB_Name);
            if (dt.Rows.Count > 0)
            {
                userId = int.Parse(dt.Rows[0]["Client_Id"].ToString());
            }
            return CommonBll.BuildShopId(userId).ToString();
        }

        //加载评论
        [AjaxPro.AjaxMethod(AjaxPro.HttpSessionStateRequirement.ReadWrite)]
        public string LoadComment(string productId)
        {
            int proId;
            Dictionary<string, object> jsonResult = new Dictionary<string, object>();
            if (int.TryParse(EncryptHelper.DecryptString(productId), out proId))
            {
                StringBuilder builder=new StringBuilder();
                Dictionary<string, object> dicWhere=new Dictionary<string, object>();
                dicWhere.Add("Product_Id",proId);
                dicWhere.Add("Comment_Status",1);
                var dtComment = CommentInfoBll.GetCommentInfoTable("*", dicWhere, CommonConst.DB_Name);
                foreach (DataRow row in dtComment.Rows)
                {
                    builder.Append("<div class=\"bh-zzg-cpck-plnr1\"><dl>");
                    builder.AppendFormat("<dt><a href=\"/shop{0}/about.html\"><img width=\"54\" height=\"54\" src=\"{1}\" /></a></dt>", CommonBll.BuildShopId(Convert.ToInt32(row["Client_Id"].ToString())), ClientInfoBll.GetClientHeader(row["User_Points"].ToString(), CommonConst.DB_Name));
                    builder.AppendFormat("<dd><a href=\"/shop{0}/about.html\">{1}</a></dd><dd>{2}</dd></dl>", CommonBll.BuildShopId(Convert.ToInt32(row["Client_Id"].ToString())), row["Client_Name"], ClientInfoBll.GetClientLevel(row["User_Points"].ToString(), CommonConst.DB_Name));
                    builder.Append("<div class=\"bh-zzg-cpck-plnr1r\">");
                    builder.AppendFormat("<dl><dt>{0}</dt>", Convert.ToDateTime(row["Comment_Date"]).ToString("yyyy-MM-dd HH:mm"));
                    builder.AppendFormat("<dd>{0}</dd></dl>", row["Comment_Note"]);
                    builder.Append("</div><div class=\"bh-clear\"></div></div>");
                }
                jsonResult.Add("isreload", true);
                jsonResult.Add("msg", builder.ToString());
            }
            else
            {
                jsonResult.Add("isreload", false);
                jsonResult.Add("msg", "参数错误！");
            }
            
            return "[" + JsonHelper.ObjectToJSON(jsonResult) + "]";
        }

        //留言
        [AjaxPro.AjaxMethod(AjaxPro.HttpSessionStateRequirement.ReadWrite)]
        public string LeaveMsg(string json)
        {
            Dictionary<string, object> jsonResult = new Dictionary<string, object>();
            try
            {
                var userInfo = WebMasterCookie.GetCookie();
                if (userInfo != null)
                {
                    var dicProj = JsonHelper.JSONToObject<Dictionary<string, object>>(json);
                    var proId = EncryptHelper.DecryptString(dicProj["product_id"].ToString());
                    var content = Server.HtmlEncode(dicProj["comment_note"].ToString()).Replace("\n/", "<br/>");
                    dicProj.Remove("comment_note");
                    dicProj.Add("comment_note", content);
                    dicProj.Remove("product_id");
                    dicProj.Add("product_id", proId);
                    dicProj.Add("client_id", userInfo.Id);
                    dicProj.Add("comment_status", 1);

                    //判断用户最后一次评论该产品的时间
                    var dtcomment = CommentInfoBll.GetCommentInfoTable("top 1 *", "Client_Id=" + userInfo.Id + " and Product_Id=" + proId, "Comment_Id desc", CommonConst.DB_Name);
                    if (dtcomment.Rows.Count > 0 && ((Convert.ToDateTime(dtcomment.Rows[0]["Comment_Date"]) - DateTime.Now).Days * 24 + (Convert.ToDateTime(dtcomment.Rows[0]["Comment_Date"]) - DateTime.Now).Hours)< 2)
                    {
                        jsonResult.Add("isreload", false);
                        jsonResult.Add("msg", "2小时内不能连续对同一产品发表评论！");
                    }
                    else
                    {
                        CommentInfoBll.InsertCommentInfo(dicProj, CommonConst.DB_Name);
                        //评论加分
                        //判断是否为当前登录用户的产品
                        var dt = ProductInfoBll.GetProductInfoTable("Client_Id=" + userInfo.Id + " and Product_Id=" + proId, "", CommonConst.DB_Name);
                        if (dt.Rows.Count == 0)
                        {
                            ClientInfoBll.UpdateClientPoints(userInfo.Id, CommonConst.gLeavePoints,"+", CommonConst.DB_Name);
                        }
                        jsonResult.Add("isreload", true);
                        jsonResult.Add("msg", "");
                    }
                    
                }
                else
                {
                    jsonResult.Add("isreload", false);
                    jsonResult.Add("msg", "请登录后留言！");
                }
            }
            catch (Exception ex)
            {
                jsonResult.Clear();
                jsonResult.Add("isreload", false);
                jsonResult.Add("msg", ex.Message);
            }


            return "[" + JsonHelper.ObjectToJSON(jsonResult) + "]";
        }

        //获取产品图片信息
        [AjaxPro.AjaxMethod(AjaxPro.HttpSessionStateRequirement.ReadWrite)]
        public string GetProductImages(string proId)
        {
            Dictionary<string, object> jsonResult = new Dictionary<string, object>();
            try
            {
                var dt1 = ProductInfoBll.GetProductPic(EncryptHelper.DecryptString(proId));
                StringBuilder builder = new StringBuilder();
                foreach (DataRow row in dt1.Rows)
                {
                    builder.AppendFormat("<div class=\"bh-zzg-cpck-ckxtcn1\"> <img src=\"{0}\" /> </div>", row["Pic_Path"]);
                }
                jsonResult.Add("isreload",true);
                jsonResult.Add("msg",builder.ToString());
            }
            catch (Exception ex)
            {
                jsonResult.Clear();
                jsonResult.Add("isreload", false);
                jsonResult.Add("msg", ex.Message);
            }
            return "[" + JsonHelper.ObjectToJSON(jsonResult) + "]";
        }


        [AjaxPro.AjaxMethod(AjaxPro.HttpSessionStateRequirement.ReadWrite)]
        public string UserLogin(string account, string pwd)
        {
            Dictionary<string, object> jsonResult = new Dictionary<string, object>();
            try
            {
                //判断用户是否已经登录
                var userInfo = WebMasterCookie.GetCookie();
                if (userInfo != null)
                {
                    jsonResult.Add("isreload", true);
                    jsonResult.Add("msg", GetUserInfo());
                }
                else
                {
                    DataTable table = ClientInfoBll.ClientLogin(CommonBll.InputText(account, 50),
                                                                EncryptHelper.EncryptString(pwd),  CommonConst.DB_Name);
                    if (table.Rows.Count > 0)
                    {
                        //判断当天是否已经登录过
                        if (table.Rows[0]["LastLoginTime"] == DBNull.Value ||
                            (Convert.ToDateTime(table.Rows[0]["LastLoginTime"].ToString()) - DateTime.Now).Days != 0)
                        {
                            //登录时积分+5并更新等级
                            ClientInfoBll.UpdateClientPoints(table.Rows[0]["Client_Id"].ToString(), CommonConst.gLoginPoints,"+",  CommonConst.DB_Name);
                            //更新最后登录时间
                            ClientInfoBll.UpateLastLoginTime(table.Rows[0]["Client_Id"].ToString(),  CommonConst.DB_Name);
                        }

                        jsonResult.Add("isreload", true);
                        var info = new UserInfo
                        {
                            Email =table.Rows[0]["User_Email"] == DBNull.Value? "": table.Rows[0]["User_Email"].ToString(),
                            Id = table.Rows[0]["Client_Id"].ToString(),RelName =table.Rows[0]["Client_Name"] == DBNull.Value? "": table.Rows[0]["Client_Name"].ToString(),
                            Status = table.Rows[0]["User_Status"].ToString(),UName = table.Rows[0]["Client_Account"].ToString()
                        };
                        info.Computername = HttpContext.Current.Application["computername"].ToString();
                        info.Computerip = HttpContext.Current.Application["computerip"].ToString();
                        WebMasterCookie.AddCookie(info);

                        Dictionary<string, object> dicLoginLog = new Dictionary<string, object>();
                        dicLoginLog.Add("user_id", info.Id);
                        dicLoginLog.Add("computername", info.Computername);
                        dicLoginLog.Add("computerip", info.Computerip);
                        LogLoginBll.AddLoginLog(dicLoginLog, CommonConst.DB_Name);
                        jsonResult.Add("msg", GetUserInfo());
                    }
                    else
                    {
                        jsonResult.Clear();
                        jsonResult.Add("isreload", false);
                        jsonResult.Add("msg", "用户名或密码错误！");
                    }
                }

            }
            catch (Exception ex)
            {
                jsonResult.Clear();
                jsonResult.Add("isreload", false);
                jsonResult.Add("msg", ex.Message);
            }
            return "[" + JsonHelper.ObjectToJSON(jsonResult) + "]";

        }

        //验证验证码是否正确
        [AjaxPro.AjaxMethod(AjaxPro.HttpSessionStateRequirement.ReadWrite)]
        public string VerificationCode(string code)
        {
            Dictionary<string, object> jsonResult = new Dictionary<string, object>();
            string verCode = Session["VerificationCode"] == null ? "" : Session["VerificationCode"].ToString();
            if (verCode.ToLower() == code.ToLower())
            {
                jsonResult.Add("isreload", true);
            }
            else
            {
                jsonResult.Add("isreload", false);
            }
            return "[" + JsonHelper.ObjectToJSON(jsonResult) + "]";
        }

        [AjaxPro.AjaxMethod(AjaxPro.HttpSessionStateRequirement.ReadWrite)]
        public string GetUserInfo()
        {
            Dictionary<string, object> jsonResult = new Dictionary<string, object>();
            var userInfo = WebMasterCookie.GetCookie();
            if (userInfo != null)
            {
                StringBuilder builder = new StringBuilder();
                builder.AppendFormat("<div class=\"acc\">欢迎您：<a target=\"_blank\" href=\"/member/message/index.html\">{0}</a>&nbsp;<a href=\"javascript:void(0);\" onclick=\"onLoginOut();\">更换用户</a></div>",
                                     userInfo.UName);
                jsonResult.Add("msg", builder.ToString());
            }
            else
            {

                jsonResult.Add("msg", "");
            }
            return "[" + JsonHelper.ObjectToJSON(jsonResult) + "]";
        }

        //广告
        [AjaxPro.AjaxMethod(AjaxPro.HttpSessionStateRequirement.ReadWrite)]
        public string GetADList()
        {
            var dic = new Dictionary<string, object>();
            dic.Add("ad10_2", "<img src=\"../../image/private/pic-11.jpg\" width=\"214px\" height=\"146px\" />");
            dic.Add("ad10_3", "<img src=\"../../image/private/pic-11.jpg\" width=\"214px\" height=\"146px\" />");
            dic.Add("ad10_4", "<img src=\"../../image/private/pic-11.jpg\" width=\"214px\" height=\"146px\" />");
            dic.Add("ad10_5", "<img src=\"../../image/private/pic-11.jpg\" width=\"214px\" height=\"146px\" />");
            dic.Add("ad10_6", "<img src=\"../../image/private/pic-11.jpg\" width=\"214px\" height=\"146px\" />");
            dic.Add("ad10_7", "<img src=\"../../image/private/pic-11.jpg\" width=\"214px\" height=\"146px\" />");
            dic.Add("ad10_8", "<img src=\"../../image/private/pic-11.jpg\" width=\"214px\" height=\"146px\" />");

            var dt = CommonBll.GetdtList("select * from ads where adid=10 and  endtime>=getdate() order by adid,sort", CommonConst.DB_Name);
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                switch (dt.Rows[i]["adid"].ToString())
                {
                    case "10"://产品214*146 
                        if (string.IsNullOrEmpty(dt.Rows[i]["url"].ToString()))
                        {
                            if ("2,3,4,5,6,7,8".Contains(dt.Rows[i]["sort"].ToString()))
                                dic["ad10_" + dt.Rows[i]["sort"].ToString()] = string.Format("<img src=\"{0}\" width=\"{1}\" height=\"{2}\" title=\"{3}\" />", dt.Rows[i]["picture"].ToString(), dt.Rows[i]["width"].ToString(), dt.Rows[i]["height"].ToString(), dt.Rows[i]["content"].ToString());
                        }
                        else
                        {
                            if ("2,3,4,5,6,7,8".Contains(dt.Rows[i]["sort"].ToString()))
                                dic["ad10_" + dt.Rows[i]["sort"].ToString()] = string.Format("<a href=\"{0}\" target=\"_blank\" title=\"{1}\"><img src=\"{2}\" width=\"{3}\" height=\"{4}\" /></a>", dt.Rows[i]["url"].ToString(), dt.Rows[i]["content"].ToString(), dt.Rows[i]["picture"].ToString(), dt.Rows[i]["width"].ToString(), dt.Rows[i]["height"].ToString());
                        }
                        break;
                }

            }
            return "[" + JsonHelper.ObjectToJSON(dic) + "]";
        }
    }
}
